package com.woniu.consumer;

import com.rabbitmq.client.Channel;
import com.woniu.entity.Registration;
import com.woniu.mapper.RegistrationMapper;
import com.woniu.utils.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class AddRegistrationConsume {
    @Resource
    private RedisTemplate redisTemplateInit;
    @Resource
    private RegistrationMapper registrationMapper;

    @RabbitListener(queues = {ConstantUtil.QUEUE_ORDER})
    public void consume(Registration msg, Channel channel, Message message){
        log.info("收到挂号订单消息：{}",msg);
        try {
                String rsNo = msg.getRsNo();
            Object o = redisTemplateInit.opsForValue().get("registration:" + rsNo);
            if (o != null) {
                registrationMapper.insertSelective(msg);
                redisTemplateInit.delete("registration:" + rsNo);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
